package com.zhengaz.service.es.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zhengaz.common.es.dto.PageModelDto;
import com.zhengaz.common.es.unils.EsUtils;
import com.zhengaz.service.es.entity.Goods;
import com.zhengaz.service.es.service.BasicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhengzg
 * @create 2023-09-18 14:36
 */
@Slf4j
@Service
public class BasicServiceImpl implements BasicService {

    @Resource
    private EsUtils esUtils;

    @Override
    public boolean createIndex(String indexName) {
        return esUtils.createIndexAndCreateMapping(indexName, Goods.class, false);
    }

    @Override
    public boolean add(String indexName, Goods goods) {
        // 判断索引是否存在
        boolean indexExists = esUtils.isIndexExists(indexName);
        if (!indexExists) {
            this.createIndex(indexName);
        }

        return esUtils.saveData(indexName, StrUtil.uuid().replace("-", ""), JSONUtil.toJsonStr(goods), Goods.class);
    }

    @Override
    public boolean delete(String indexName, String id) {
        return esUtils.deleteDate(indexName, StrUtil.toString(id));
    }

    @Override
    public boolean update(String indexName, String id, Goods newGoods) {
        return esUtils.updateData(indexName, StrUtil.toString(id), JSONUtil.toJsonStr(newGoods));
    }

    @Override
    public List<Goods> search(String indexName) {
        PageModelDto pageModelDto = new PageModelDto();
        Map<String, Object> equalsSearch = new HashMap<>();
        equalsSearch.put("name","华为mate60 pro");
        pageModelDto.setEqualsSearchCondition(equalsSearch);
        PageModelDto resultDto = esUtils.queryData(pageModelDto, indexName);
        List<String> jsonRsList = resultDto.getJsonRsList();

        return jsonRsList.stream().map(json -> JSONUtil.toBean(json, Goods.class)).collect(Collectors.toList());
    }
}
